
import os
from PIL import Image
import sys


def get_imlist(path, fmt_input):
    return [os.path.join(path, f) for f in os.listdir(path) if f.endswith(fmt_input)]


def convert_image_fmt(path, fmt_input, fmt_output):
    im_list = get_imlist(path, fmt_input)
    for infile in im_list:
        outfile = os.path.splitext(infile)[0] + fmt_output
        if infile != outfile:
            try:
                Image.open(infile).save(outfile)
                os.remove(infile)
            except IOError:
                    print("cannot convert", infile)

def main():

    if len(sys.argv)<2:
        print ('''======================================================================
    ===    usage:python3 to run                                        ===  
    ===          path inputformat outputformat                         ===
    ===    example:                                                    ===
    ===          py      formatChange.py D:Phtot pgm jpg               ===
    ======================================================================''')
    else:
        path = sys.argv[1]
        fmt_input = '.' + sys.argv[2]
        fmt_output = '.' + sys.argv[3]
        print (path,fmt_input,fmt_output)
        print (get_imlist(path, fmt_input))
        convert_image_fmt(path, fmt_input, fmt_output)

if __name__ == '__main__':
    main()
    #images = get_imlist("d:\\Pictures\\3dREc\\corridor",".jpg")
    #print(images)

#path = 'd:\\Pictures\\3dREc\\corridor\\'
#fmt_input = '.pgm'
#fmt_output = '.jpg'

